package cn.sc.summer.seata.config;

import cn.sc.summer.seata.service.SeataService;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import cn.sc.summer.resource.constant.PropertyConstant;
import cn.sc.summer.resource.factory.YamlPropertySourceFactory;
import com.alibaba.nacos.api.exception.NacosException;
import io.seata.spring.boot.autoconfigure.SeataAutoConfiguration;
import io.seata.spring.boot.autoconfigure.properties.SeataProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 类名：初始化配置seata自定义文件
 *
 * @author a-xin
 * @date 2023/12/1 09:44
 */
@Slf4j
@Configuration
@PropertySource(value = PropertyConstant.SEATA_PATH, factory = YamlPropertySourceFactory.class)
@AutoConfigureBefore(value = SeataAutoConfiguration.class)
@EnableConfigurationProperties({SeataProperties.class, NacosConfigProperties.class})
public class SeataConfig {

    /**
     * 初始化seata对应的单个服务项的分布式事务组
     *
     * @param seataProperties       seata配置文件信息
     * @param nacosConfigProperties nacos注册配置信息
     * @return 是否成功配置
     */
    @Bean
    @ConditionalOnProperty(prefix = "seata", name = "enabled", havingValue = "true")
    public boolean creatSeataConfig(SeataProperties seataProperties, NacosConfigProperties nacosConfigProperties) throws NacosException {
        log.info("==> Start initializing the SEATA distributed transaction profile!");
        return SeataService.creatSeataConfig(seataProperties, nacosConfigProperties);
    }

    /**
     * 关闭seata后会删除指定的配置项文件
     *
     * @param seataProperties       seata配置文件信息
     * @param nacosConfigProperties nacos注册配置信息
     * @return 是否成功配置
     */
    @Bean
    @ConditionalOnProperty(prefix = "seata", name = "enabled", havingValue = "false")
    public boolean delSeataConfig(SeataProperties seataProperties, NacosConfigProperties nacosConfigProperties) throws NacosException {
        log.info("==> Start delete the SEATA config file!");
        return SeataService.deleteSeataConfig(seataProperties, nacosConfigProperties);
    }

}
